package com.globallogic.vacationplanner.model.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.globallogic.vacationplanner.model.dao.declaration.IBaseDao;

public abstract class BaseDao<T> extends HibernateDaoSupport implements
		IBaseDao<T> {

	private static final long serialVersionUID = 3187458415733206807L;
	private static Logger LOGGER = Logger.getLogger(BaseDao.class);

	public BaseDao() {
		super();
		LOGGER.info("BaseDao created");
	}

	@Autowired
	public void injectSessionFactory(SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
		LOGGER.info("session factory has been injected");
	}

	@Transactional
	@Override
	public void insert(T obj) throws HibernateException {
		LOGGER.info("create user");
		try {
			getHibernateTemplate().save(obj);
		} catch (HibernateException hibException) {
			LOGGER.error("create user failed");
			throw hibException;
		}
		LOGGER.info("create user successful");
	}

	@Override
	public void delete(int id) {
	}
	
	@Override
	public void delete(T object) {
		getHibernateTemplate().delete(object);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T read(T template) {
		List<T> objects = getHibernateTemplate().findByExample(template);
		return objects.isEmpty() ? null : (T) objects.get(0);
	}

	@Override
	public void update(T obj) {

	}

	@SuppressWarnings("unchecked")
	public List<T> readAll() {
		List<T> userList = getHibernateTemplate().find(getReadAllQuery());
		LOGGER.info("get List of Users");
		return userList;
	}

	abstract String getReadAllQuery();
}
